/**
 * @author
 * @description 公共请求方法
 */
import store from '../utils/store.js';

const system = store.getSystemInfo();
const clientInfo = {
  clientType: 'mp',
  appnm: 'gkcd',
  model: system.model,
  os: system.system,
  screen: `${system.screenWidth}*${system.screenHeight}`,
  version: App.version,
  channel: 'miniprogram'
};

const errMsg = '服务异常，请稍后重试';

const fetch = async (url, data = {}, option = {}) => {
  const { loading = true, toast = true, isMock = false, method = 'GET' } = option;
  const env = isMock ? App.config.chargeApi : App.config.baseApi;

  if (loading) {
    // uni.showLoading({
    //   title: '加载中...',
    //   mask: true
    // });
  }

  try {
    const response = await new Promise((resolve, reject) => {
      uni.request({
        url: env + url,
        data,
        method,
        header: {
          clientInfo: JSON.stringify(clientInfo)
        },
        success: (result) => {
          if (loading) {
            uni.hideLoading();
          }
          const res = result.data;
          if (res.code === 0) {
            resolve(res.data); // 传递逻辑数据
          } else {
            reject(res); // 传递异常
          }
        },
        fail: (e) => {
          if (loading) {
            uni.hideLoading();
          }
          let msg = e.errMsg;
          if (msg === 'request:fail timeout') {
            msg = '服务请求超时，请稍后处理';
          }
          if (toast) {
            uni.showToast({
              title: msg,
              icon: 'none'
            });
          }
          reject({
            code: -1,
            msg,
            errMsg: errMsg
          });
        }
      });
    });
    return response;
  } catch (error) {
    console.error('Request failed:', error);
    throw error;
  }
};

export default {
  fetch
};
